package net.zjitc.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/11/20.
 */
@WebServlet(name = "FileUpLoadServlet",urlPatterns = "/fileUpLoadServlet")
public class FileUpLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.工厂
        DiskFileItemFactory factory  = new DiskFileItemFactory();
        //2. 解析器
        ServletFileUpload sf = new ServletFileUpload(factory);  //IO 装饰设计模式 23
        sf.setHeaderEncoding("utf-8");
        //3.解析
        try {
            //3.1 得到FileItem列表
            List<FileItem> list =sf.parseRequest(request);
            for (FileItem item:list){
                //3.2 判断是否是普通表单
               if (item.isFormField()){
                   String fieldName = item.getFieldName(); //获得的是当前input类型的字段的名称username

                   if ("username".equals(fieldName)){
                       String value = item.getString("utf-8"); //username--->value
                       System.out.println(value);
                   }
               }else { //文件类型
                   String name = item.getName(); //获得的是文件名
                   System.out.println("---------------------");
                   System.out.println(name);
                   System.out.println(item.getContentType());
                   InputStream inputStream = item.getInputStream();//得到的文件内容是输入流的方式

                   //将输入流保存到文件中，文件名与原上传的文件名相同
                   String savePath = this.getServletContext().getRealPath("/image");
                        // savePath ---> D:\file\target\file\image
                   File dir = new File(savePath);
                   if (!dir.exists()){
                       dir.mkdirs();
                   }
                   //使用UUID产生唯一标识
                   String uuid = UUID.randomUUID().toString().replace("-","");
                   //75e477bd6b16482095f0b93c25511714-name.jpg
                   //构造保存的文件名，使用UUID作为标识
                   String fileName = uuid+"-"+item.getName();
                   //保存到UUID的文件名下
                   File file = new File(dir,fileName);
                   item.write(file);


                   //imgPath = 路径+名字
                   String imgPath = "image"+"\\"+fileName;
                   request.setAttribute("imgPath",imgPath);
                   request.getRequestDispatcher("/test/show.jsp").forward(request,response);

                   System.out.println("uuid = "+uuid);


                   System.out.println("============================");
                   //通过IO工具，把输入流转成字符串
                   String s = IOUtils.toString(inputStream);
                   System.out.println(s);
                   //
               }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
